#pyinstaller --hiddenimport win32timezone -F get_sntins.py


import base64
import win32com.client
import os
import json
import datetime
import time
#import jwt
import xlwt


CADES_BES = 1
CADES_DEFAULT = 0
CAPICOM_ENCODE_BASE64 = 0
CAPICOM_CURRENT_USER_STORE = 2
CAPICOM_MY_STORE = 'My'
CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED = 2

ExtensionList=['beer','water','softdrinks']

#https://markirovka.crpt.ru/
#019606DD00C5AFD1B74D3BDB07DA28919F
#0531A7910081B148A0497C9D7E233DFC74
#3

oStore = win32com.client.Dispatch("CAdESCOM.Store")
oStore.Open(CAPICOM_CURRENT_USER_STORE, CAPICOM_MY_STORE, CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED)
'''
for val in oStore.Certificates:
   # print(val.SerialNumber )
    if val.SerialNumber == "019606DD00C5AFD1B74D3BDB07DA28919F":
        oCert = val
oStore.Close
'''

print('Выберети номер сертификата')

for i,val in enumerate(oStore.Certificates):
    print('')
    print(i,val.SubjectName)
    print('')
oCert = oStore.Certificates[int(input())] 
print(oCert.SerialNumber)
print('')

#4
oSigner = win32com.client.Dispatch("CAdESCOM.CPSigner")
oSigner.Certificate = oCert
oSigningTimeAttr = win32com.client.Dispatch("CAdESCOM.CPAttribute")
oSigningTimeAttr.Name = 0
oSigningTimeAttr.Value = datetime.datetime.now()
oSigner.AuthenticatedAttributes2.Add(oSigningTimeAttr)





#5
#markirovka.crpt.ru/

url = "https://markirovka.crpt.ru/api/v3/true-api/auth/key" 
params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.Send(json.dumps(params))
win_http.WaitForResponse()
#print(win_http.ResponseText)
items  = json.loads(win_http.ResponseText)
CodeAuth = items['data']

                                   
#6
                                   
oSignedData = win32com.client.Dispatch("CAdESCOM.CadesSignedData")
oSignedData.ContentEncoding = 1
message = CodeAuth
message_bytes = message.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')
oSignedData.Content = base64_message
sSignedData = oSignedData.SignCades(oSigner, CADES_BES, False, CAPICOM_ENCODE_BASE64)

#7
url = "https://markirovka.crpt.ru/api/v3/true-api/auth/simpleSignIn/9e305a5d-f8c4-40dc-8e0e-273885de03a7"

paramskey ={
  'uuid': items['uuid'],
  'data': sSignedData
}

win_http.Open("POST", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.Send(json.dumps(paramskey))
win_http.WaitForResponse()
#print(win_http.ResponseText)
token =json.loads(win_http.ResponseText)["token"]
#print(token)
#c1db5da8-ff8f-4b6f-8602-844214303d25
print('-'*30)
print('1 - пиво')
print('2 - вода')
print('3 - безалкоголка')
choice = int(input())-1
extension=ExtensionList[choice]
print('-'*30)
print('Номер нанесения')
resultDocId=input()

url ='https://suz.crpt.ru/api/v2/'+extension+'/receipts/receipt?resultDocId='+resultDocId+'&omsId=f081cfb0-d86b-47a5-9515-84636e4bfd80'

params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("clientToken",token)

win_http.Send(json.dumps(params))
win_http.WaitForResponse()
#print(win_http.ResponseText)
docId  = json.loads(win_http.ResponseText)['results'][0]['sourceDocId']
#print(items)

url ='https://suz.crpt.ru/api/v2/'+extension+'/receipts/document?resultDocId='+resultDocId + '&docId='+docId+'&omsId=f081cfb0-d86b-47a5-9515-84636e4bfd80'

params = {}
win_http = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
win_http.Open("GET", url, False)
win_http.SetRequestHeader("Content-Type","application/json;charset=UTF-8")
win_http.SetRequestHeader("Accept","application/json;charset=UTF-8")
win_http.SetRequestHeader("clientToken",token)

win_http.Send(json.dumps(params))
win_http.WaitForResponse()
#print(win_http.ResponseText)
sntins  = json.loads(json.loads(win_http.ResponseText)['content'])['sntins']

#aaa = "{\"@class\":\"com.equiron.sitemanager.api.v2.model.report.UtilisationReportDtoBeer\",\"sntins\":[\"0104607004639661215zf!,Wh\",\"0104607004639661215Z/!Bi%\",\"0104607004639661215ZaT6qM\",\"0104607004639661215\\\"ZzpN=\",\"0104607004639661215Zht<=S\"],\"usageType\":\"VERIFIED\",\"participantId\":\"4345000224\",\"productionDate\":\"13.12.2023\",\"expirationDate\":\"05.05.2024\",\"kpp\":\"434501001\",\"fiasId\":\"6f1aef5a-c3bb-4279-bc5c-3c0fd7ee0512\"}"
#b = json.loads(aaa)

wb = xlwt.Workbook()
ws = wb.add_sheet('sntins')
j=0
for i in sntins:
    ws.write(j, 0, i)
    j+=1
wb.save(resultDocId+'_sntins.xls')
os.system(resultDocId+'_sntins.xls')

'''
with open('km.txt','w+')  as f:
    for i in sntins:
        f.write(i+'\n')
os.system('km.txt')
'''
